package org.springblade.modules.repair.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.message.MessageCenterUtils;
import org.springblade.common.utils.message.domain.MessageParam;
import org.springblade.common.utils.message.domain.SendRequest;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.repair.dto.ByScoreQuestionAppealSearchDTO;
import org.springblade.modules.repair.entity.*;
import org.springblade.modules.repair.enums.ByScoreQuestionAppealEnum;
import org.springblade.modules.repair.mapper.MaintainByScoreQuestionAppealMapper;
import org.springblade.modules.repair.service.*;
import org.springblade.modules.repair.vo.ByScoreQuestionAppealPageVO;
import org.springblade.modules.repair.vo.PlanAbarbeitungByContentVO;
import org.springblade.modules.system.entity.TenantConfig;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.service.TenantConfigService;
import org.springblade.modules.system.vo.SimpleUserVO;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@AllArgsConstructor
@Service
public class ByScoreQuestionAppealServiceImpl extends BaseServiceImpl<MaintainByScoreQuestionAppealMapper, MaintainByScoreQuestionAppeal> implements ByScoreQuestionAppealService {

	@Lazy
	private final IMaintainByScoreQuestionService byScoreQuestionService;
	private final TenantConfigService tenantConfigService;
	private final IUserService userService;
	private final ElevatorDetailService elevatorDetailService;
	private final IBuildingService buildingService;
	private final MessageCenterUtils messageCenterUtils;
	private final Environment environment;

	@Override
	public IPage<ByScoreQuestionAppealPageVO> selectPage(IPage<ByScoreQuestionAppealPageVO> page, ByScoreQuestionAppealSearchDTO searchDTO) {
		return page.setRecords(baseMapper.page(page,searchDTO));
	}

	@Override
	public List<PlanAbarbeitungByContentVO> selectDetailItem(Long id) {
		MaintainByScoreQuestionAppeal entity = super.getById(id);
		if(Func.isEmpty(entity)){
			throw new ServiceException("业务数据不存在");
		}
		return baseMapper.selectistoryList(entity.getPlanId(),entity.getAppealStatus());
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Boolean submit(MaintainByScoreQuestionAppeal appeal) {

		MaintainByScoreQuestionAppeal entity = super.getById(appeal.getId());
		if(Func.isEmpty(entity)){
			throw new ServiceException("业务数据不存在");
		}
		if(ByScoreQuestionAppealEnum.APPEAL_STATUS_1.getId() != entity.getAppealStatus()){
			throw new ServiceException("业务状态已变更，请刷新页面");
		}

		appeal.setBuildingId(entity.getBuildingId());
		appeal.setPlanId(entity.getPlanId());
		appeal.setElevatorId(entity.getElevatorId());
		appeal.setAppealStatus(ByScoreQuestionAppealEnum.APPEAL_STATUS_2.getId());
		appeal.setAppealResult(ByScoreQuestionAppealEnum.APPEAL_RESULT_1.getId());
		appeal.setAppealUserId(AuthUtil.getUserId());
		appeal.setAppealUserName(AuthUtil.getNickName());
		appeal.setAppealTime(DateUtil.date());

		List<MaintainByScoreQuestion> byScoreQuestions = byScoreQuestionService.list(Wrappers.<MaintainByScoreQuestion>lambdaQuery().eq(MaintainByScoreQuestion::getPlanId,entity.getPlanId()));
		byScoreQuestions.forEach(e -> e.setAppealId(appeal.getId()));
		byScoreQuestionService.updateBatchById(byScoreQuestions);

		this.sendSubmitMsg(appeal);
		return super.updateById(appeal);
	}

	private void sendSubmitMsg(MaintainByScoreQuestionAppeal appeal) {
		TenantConfig tenantConfig = tenantConfigService.getTenantConfig(AuthUtil.getTenantId());
		ElevatorDetail elevatorDetail = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId,appeal.getElevatorId()));
		Building building = buildingService.getById(appeal.getBuildingId());
		String curEnvironment = environment.getActiveProfiles()[0];
		if(Func.isNotEmpty(tenantConfig.getZgRedeployConfig().getApproverUsers())){
			List<SimpleUserVO> userList = userService.listUserSimpleInfo(tenantConfig.getZgRedeployConfig().getApproverUsers().stream().map(ByAppealApproverUser::getId).collect(Collectors.toList()));
			userList.forEach(e -> {
				if(Func.isNotEmpty(e.getOpenid())){
					String templateId;
					//当前环境
					if (Func.equalsSafe(curEnvironment, "prod")) {
						// 正式环境
						templateId = "1925449574010425346";
					}else {
						templateId = "1925383186450821121";
					}
					Map<String, String> contentMap = new HashMap<>(4);
					contentMap.put("thing1", building.getName()+elevatorDetail.getElevatorAddress());
					contentMap.put("character_string2", "保养问题申诉");
					contentMap.put("time3", DateUtil.formatDateTime(DateUtil.date()));
					// 构造消息
					String url = String.format("/subpages/correction/appealDetail?planId=%s&elevatorId=%s&id=%s",appeal.getPlanId(),appeal.getElevatorId(),appeal.getId());
					Map<String, String> variablesMap = new HashMap<>(4);
					variablesMap.put("content", JSONObject.toJSONString(contentMap));
					variablesMap.put("url", url);
					variablesMap.put(BladeConstant.MDC_TENANT_ID_KEY, "592800");
					// 维保小程序appid
					variablesMap.put("miniProgramId", "wxb8dc0f5451620604");

					SendRequest sendRequest = SendRequest.builder()
						.messageTemplateId(templateId)
						.messageParam(MessageParam.builder()
							.receiver(String.valueOf(e.getOpenid()))
							.variables(variablesMap)
							.build())
						.build();
					R r = messageCenterUtils.sendMessage(sendRequest);
					log.info("公众号推送结果:" + JSON.toJSONString(r));
				}
				if(Func.isNotEmpty(e.getRegistrationId())){
					String templateId;
					//当前环境
					if (Func.equalsSafe(curEnvironment, "prod")) {
						// 正式环境
						templateId = "1925449383576440834";
					}else {
						templateId = "1925384818794246146";
					}
					Map<String, String> contentMap = new HashMap<>(4);
					contentMap.put("title", "保养工单申诉审批");
					contentMap.put("content", String.format("您收到【%s%s】保养工单问题申诉审批",building.getName(),elevatorDetail.getElevatorAddress()));
					contentMap.put("url", String.format("/subpages/correction/appealDetail?planId=%s&elevatorId=%s&id=%s",appeal.getPlanId(),appeal.getElevatorId(),appeal.getId()));
					contentMap.put(BladeConstant.MDC_TENANT_ID_KEY, "592800");
					SendRequest request = SendRequest.builder()
						.messageTemplateId(templateId)
						.messageParam(
							MessageParam.builder()
								.receiver(String.valueOf(e.getRegistrationId()))
								.variables(contentMap)
								.build()
						).build();
					R r = messageCenterUtils.sendMessage(request);
					log.info("APP推送结果:" + JSON.toJSONString(r));
				}
				if(Func.isNotEmpty(e.getPhone())){
					String templateId;
					//当前环境
					if (Func.equalsSafe(curEnvironment, "prod")) {
						// 正式环境
						templateId = "1925451551083696129";
					}else {
						templateId = "1925450170509111298";
					}
					Map<String, String> contentMap = new HashMap<>(4);
					contentMap.put("content", "保养整改问题申诉");
					contentMap.put(BladeConstant.MDC_TENANT_ID_KEY, "592800");
					SendRequest sendRequest = SendRequest.builder()
						.messageTemplateId(templateId)
						.messageParam(MessageParam.builder()
							.receiver(e.getPhone())
							.variables(contentMap)
							.build())
						.build();
					R r = messageCenterUtils.sendMessage(sendRequest);
					log.info("梯无忧PC推送结果:" + JSON.toJSONString(r));
				}
			});
		}
	}

	@Override
	public Boolean submitResult(MaintainByScoreQuestionAppeal appeal) {
		MaintainByScoreQuestionAppeal entity = super.getById(appeal.getId());
		if(Func.isEmpty(entity)){
			throw new ServiceException("业务数据不存在");
		}
		if(ByScoreQuestionAppealEnum.APPEAL_STATUS_2.getId() != entity.getAppealStatus()){
			throw new ServiceException("业务状态已变更，请刷新页面");
		}

		entity.setApproverDesc(appeal.getApproverDesc());
		entity.setAppealResult(appeal.getAppealResult());
		entity.setApproverUserId(AuthUtil.getUserId());
		entity.setApproverUserName(AuthUtil.getNickName());
		entity.setApproverTime(DateUtil.date());

		this.sendSubmitResultMsg(entity);
		return super.updateById(entity);
	}

	private void sendSubmitResultMsg( MaintainByScoreQuestionAppeal appeal) {
		ElevatorDetail elevatorDetail = elevatorDetailService.getOne(Wrappers.<ElevatorDetail>lambdaQuery().eq(ElevatorDetail::getElevatorId,appeal.getElevatorId()));
		Building building = buildingService.getById(appeal.getBuildingId());
		SimpleUserVO userVO = userService.getSimpleUserInfo(appeal.getAppealUserId());
		String curEnvironment = environment.getActiveProfiles()[0];
		String appealResultStr = appeal.getAppealResult() == ByScoreQuestionAppealEnum.APPEAL_RESULT_2.getId() ? "审核通过" : "审核不通过";
		if(Func.isNotEmpty(userVO.getOpenid())){
			String templateId;
			//当前环境
			if (Func.equalsSafe(curEnvironment, "prod")) {
				// 正式环境
				templateId = "1925449574010425346";
			}else {
				templateId = "1925383186450821121";
			}
			Map<String, String> contentMap = new HashMap<>(4);
			contentMap.put("thing1", building.getName()+elevatorDetail.getElevatorAddress());
			contentMap.put("character_string2", String.format("保养问题申诉-%s",appealResultStr));
			contentMap.put("time3", DateUtil.formatDateTime(DateUtil.date()));
			// 构造消息
			String url = String.format("/subpages/correction/appealDetail?planId=%s&elevatorId=%s&id=%s",appeal.getPlanId(),appeal.getElevatorId(),appeal.getId());
			Map<String, String> variablesMap = new HashMap<>(4);
			variablesMap.put("content", JSONObject.toJSONString(contentMap));
			variablesMap.put("url", url);
			variablesMap.put(BladeConstant.MDC_TENANT_ID_KEY, "592800");
			// 维保小程序appid
			variablesMap.put("miniProgramId", "wxb8dc0f5451620604");

			SendRequest sendRequest = SendRequest.builder()
				.messageTemplateId(templateId)
				.messageParam(MessageParam.builder()
					.receiver(String.valueOf(userVO.getOpenid()))
					.variables(variablesMap)
					.build())
				.build();
			R r = messageCenterUtils.sendMessage(sendRequest);
			log.info("公众号推送结果:" + JSON.toJSONString(r));
		}
		if(Func.isNotEmpty(userVO.getRegistrationId())){
			String templateId;
			//当前环境
			if (Func.equalsSafe(curEnvironment, "prod")) {
				// 正式环境
				templateId = "1925449383576440834";
			}else {
				templateId = "1925384818794246146";
			}
			Map<String, String> contentMap = new HashMap<>(4);
			contentMap.put("title", String.format("保养工单申诉-%s",appealResultStr));
			contentMap.put("content", String.format("【%s%s】保养工单问题申诉%s",building.getName(),elevatorDetail.getElevatorAddress(),appealResultStr));
			contentMap.put("url", String.format("/subpages/correction/appealDetail?planId=%s&elevatorId=%s&id=%s",appeal.getPlanId(),appeal.getElevatorId(),appeal.getId()));
			contentMap.put(BladeConstant.MDC_TENANT_ID_KEY, "592800");
			SendRequest request = SendRequest.builder()
				.messageTemplateId(templateId)
				.messageParam(
					MessageParam.builder()
						.receiver(String.valueOf(userVO.getRegistrationId()))
						.variables(contentMap)
						.build()
				).build();
			R r = messageCenterUtils.sendMessage(request);
			log.info("APP推送结果:" + JSON.toJSONString(r));
		}
	}

	@Override
	public Boolean submitReason(MaintainByScoreQuestion byScoreQuestion) {
		MaintainByScoreQuestion entity = byScoreQuestionService.getById(byScoreQuestion.getId());
		entity.setAppealDesc(byScoreQuestion.getAppealDesc());
		entity.setAppealImg(byScoreQuestion.getAppealImg());
		entity.setAppealUserId(AuthUtil.getUserId());
		entity.setAppealUserName(AuthUtil.getNickName());
		entity.setAppealTime(DateUtil.date());
		return byScoreQuestionService.updateById(entity);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Boolean repeal(MaintainByScoreQuestionAppeal appeal) {
		MaintainByScoreQuestionAppeal entity = super.getById(appeal.getId());
		if(Func.isEmpty(entity)){
			throw new ServiceException("业务数据不存在");
		}
		if(ByScoreQuestionAppealEnum.APPEAL_RESULT_1.getId() != entity.getAppealResult()){
			throw new ServiceException("业务状态已变更，请刷新页面");
		}

		List<MaintainByScoreQuestion> byScoreQuestions = byScoreQuestionService.list(Wrappers.<MaintainByScoreQuestion>lambdaQuery().eq(MaintainByScoreQuestion::getPlanId,entity.getPlanId()));
		byScoreQuestions.forEach(e -> {
			e.setAppealId(null);
			e.setAppealImg(new ArrayList<>());
			e.setAppealDesc(null);
			e.setAppealUserId(null);
			e.setAppealUserName(null);
			e.setAppealTime(null);
		});

		long count = byScoreQuestions.stream().filter(e -> e.getScoreIssueStatus() == 1).count();
		if(count > 0){
			entity.setQuestionCount(byScoreQuestions.size());
			entity.setAppealType(ByScoreQuestionAppealEnum.APPEAL_TYPE_2.getId());
			entity.setAppealStatus(null);
			entity.setAppealResult(null);
			entity.setAppealUserId(null);
			entity.setAppealUserName(null);
			entity.setAppealTime(null);
		}else {
			entity.setQuestionCount(byScoreQuestions.size());
			entity.setAppealType(ByScoreQuestionAppealEnum.APPEAL_TYPE_1.getId());
			entity.setAppealStatus(ByScoreQuestionAppealEnum.APPEAL_STATUS_1.getId());
			entity.setAppealResult(null);
			entity.setAppealUserId(null);
			entity.setAppealUserName(null);
			entity.setAppealTime(null);
		}
		byScoreQuestionService.updateBatchById(byScoreQuestions);
		return super.updateById(entity);
	}

}
